package com.example.chcrm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.chcrm.entity.common.OperateRecord;
import com.example.chcrm.entity.common.RandomHelper;
import com.example.chcrm.entity.common.ResponseMsg;
import com.example.chcrm.entity.consignor.CustomerCarBrand;
import com.example.chcrm.entity.consignor.CustomerCarModel;
import com.example.chcrm.entity.employee.EmployeeVo;
import com.example.chcrm.mapper.CustomerCarBrandMapper;
import com.example.chcrm.mapper.CustomerCarModelMapper;
import com.example.chcrm.mapper.CustomerTypeMapper;
import com.example.chcrm.mapper.OperateRecordMapper;
import com.example.chcrm.service.CustomerCarModelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author 邹
 * @Date 2025/4/20 17:48
 * @Version 1.0
 */
@Service
public class CustomerCarModelServiceImpl  <T> implements CustomerCarModelService<T> {
    @Autowired
    CustomerCarModelMapper customerCarModelMapper;
    @Autowired
    CustomerCarBrandMapper customerCarBrandMapper;
    @Autowired
    OperateRecordMapper operateRecordMapper;
    /**
     * 分页查询委托车型号
     */
    @Override

    public ResponseMsg<IPage<CustomerCarModel>> carModelList(CustomerCarModel customerCarModel, EmployeeVo emp) {
        QueryWrapper<CustomerCarModel> query = new QueryWrapper<>();
        if (StringUtils.isNotBlank(customerCarModel.getBrandName())) {
            query.like("brand_name", customerCarModel.getBrandName());
        }
        if (StringUtils.isNotBlank(customerCarModel.getModel())) {
            query.like("model", customerCarModel.getModel());
        }
        if (customerCarModel.getStatus() != null) {
            query.eq("status", customerCarModel.getStatus());
        }
        if (customerCarModel.getBrandId() != null &&customerCarModel.getBrandId() != "") {
            query.eq("brand_id", customerCarModel.getBrandId());
        }
        if (customerCarModel.getIsNewEnergy() != null) {
            query.lambda().eq(CustomerCarModel::getIsNewEnergy, customerCarModel.getIsNewEnergy());
        }
        query.eq("is_deleted", 0);
        query.orderByDesc("create_time");

        List<CustomerCarModel> list = customerCarModelMapper.selectList(query);

        // 封装返回结果
        ResponseMsg<IPage<CustomerCarModel>> responseMsg = new ResponseMsg<>();
        Page<CustomerCarModel> page = new Page<>();
        page.setRecords(list);
        page.setTotal(list.size());
        page.setSize(customerCarModel.getRows());
        page.setCurrent(customerCarModel.getPage());

        responseMsg.setData(page);
        responseMsg.success("查询成功");
        return responseMsg;
    }

    /**
     * 添加委托车型号
     *
     * @param customerCarModel
     * @param empVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseMsg<Object> addCarModel(CustomerCarModel customerCarModel, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        
        // 参数校验
        if (StringUtils.isBlank(customerCarModel.getBrandId())) {
            msg.fail("品牌不能为空");
            return msg;
        }
        if (StringUtils.isBlank(customerCarModel.getModel())) {
            msg.fail("型号名称不能为空");
            return msg;
        }
        if (StringUtils.isBlank(customerCarModel.getConfig())) {
            msg.fail("配置不能为空");
            return msg;
        }
        if (customerCarModel.getWeight() == null) {
            msg.fail("重量不能为空");
            return msg;
        }
        if (customerCarModel.getLength() == null) {
            msg.fail("长度不能为空");
            return msg;
        }
        if (customerCarModel.getWidth() == null) {
            msg.fail("宽度不能为空");
            return msg;
        }
        if (customerCarModel.getHeight() == null) {
            msg.fail("高度不能为空");
            return msg;
        }

        // 查询品牌是否存在
        CustomerCarBrand carBrand = customerCarBrandMapper.selectById(customerCarModel.getBrandId());
        if (carBrand == null || carBrand.getIsDeleted() != 0) {
            msg.fail("品牌不存在");
            return msg;
        }
        customerCarModel.setBrandName(carBrand.getBrand());

        // 验证同一品牌型号是否存在
        int num = customerCarModelMapper.selectCount(new QueryWrapper<CustomerCarModel>()
                .eq("brand_id", customerCarModel.getBrandId())
                .eq("model", customerCarModel.getModel())
                .eq("is_deleted", 0)
        ).intValue();
        if (num > 0) {
            msg.fail("型号已存在");
            return msg;
        }

        // 设置默认值
        customerCarModel.setId(RandomHelper.uuid());
        customerCarModel.setStatus(1); // 默认启用
        customerCarModel.setIsDeleted(0);
        customerCarModel.setCreateTime(new Date());

        // 保存数据
        customerCarModelMapper.insert(customerCarModel);

        // 添加操作日志
        OperateRecord ope = new OperateRecord();
        ope.setId(RandomHelper.uuid());
        ope.setOperateType(OperateRecord.OPE_ADD);
        if (empVo != null) {
            ope.setOperationId(empVo.getId());
            ope.setOperationName(empVo.getEmpNm());
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ope.setCreateTime(sdf.format(new Date()));
        ope.setSourceId(customerCarModel.getId());
        operateRecordMapper.insert(ope);

        msg.success("新增成功");
        return msg;
    }

    /**
     * 详情委托车型号
     *
     * @param id
     * @return
     */
    @Override
    public ResponseMsg<Object> carModelDetail(String id) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        CustomerCarModel customerCarModel = customerCarModelMapper.selectOne(new QueryWrapper<CustomerCarModel>()
                .eq("is_deleted", 0)
                .eq("id", id));
        if (customerCarModel == null) {
            msg.fail("型号未查到");
            return msg;
        }
        QueryWrapper<OperateRecord> opQuery = new QueryWrapper<>();
        opQuery.eq("sourceId", id).orderByDesc("create_time");
        List<OperateRecord> operateRecordList = operateRecordMapper.selectList(opQuery);
        customerCarModel.setOperateRecordList(operateRecordList);
        msg.setData(customerCarModel);
        msg.success("查询成功");
        return msg;
    }

    /**
     * 修改
     *
     * @param customerCarModel
     * @param emp
     * @return
     */
    @Override
    public ResponseMsg<Object> updateCarModel(CustomerCarModel customerCarModel, EmployeeVo emp) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        //验证当前数据是否存在
        CustomerCarModel oldCustomerCarModel = customerCarModelMapper.selectOne(new QueryWrapper<CustomerCarModel>()
                .eq("is_deleted", 0)
                .eq("id", customerCarModel.getId()));
        if (oldCustomerCarModel == null) {
            msg.fail("数据不存在");
            return msg;
        }
        //验证型号名称是否存在
        int numModel = customerCarModelMapper.selectCount(new QueryWrapper<CustomerCarModel>()
                .eq("model", customerCarModel.getModel())
                .ne("id", oldCustomerCarModel.getId())
                .eq("is_deleted", 0)
                .eq("brand_id",oldCustomerCarModel.getBrandId())).intValue();
        if (numModel > 0) {
            msg.fail("添加失败，品牌+型号名称已存在");
            return msg;
        }
        //查询品牌是否存在
        if (!customerCarModel.getBrandId().equals(oldCustomerCarModel.getBrandId())) {
            CustomerCarBrand carBrand = customerCarBrandMapper.selectById(customerCarModel.getBrandId());
            if (carBrand == null || carBrand.getIsDeleted() != 0) {
                msg.fail("品牌不存在");
                return msg;
            }
            oldCustomerCarModel.setBrandId(carBrand.getId());
            oldCustomerCarModel.setBrandName(carBrand.getBrand());
        }
        //验证同一品牌型号是否存在
        int num = customerCarModelMapper.selectCount(new QueryWrapper<CustomerCarModel>()
                .eq("brand_id", oldCustomerCarModel.getBrandId())
                .ne("id", customerCarModel.getId())
                .eq("model", customerCarModel.getModel())
                .eq("is_deleted", 0)
        ).intValue();
        if (num > 0) {
            msg.fail("型号已存在");
            return msg;
        }
        oldCustomerCarModel.setModel(customerCarModel.getModel());
        oldCustomerCarModel.setConfig(customerCarModel.getConfig());
        oldCustomerCarModel.setWeight(customerCarModel.getWeight());
        oldCustomerCarModel.setLength(customerCarModel.getLength());
        oldCustomerCarModel.setWidth(customerCarModel.getWidth());
        oldCustomerCarModel.setHeight(customerCarModel.getHeight());
        oldCustomerCarModel.setIsNewEnergy(customerCarModel.getIsNewEnergy());
        customerCarModelMapper.updateById(oldCustomerCarModel);
        //添加操作日志
        OperateRecord ope = new OperateRecord();
        ope.setId(RandomHelper.uuid());
        if (emp != null) {
            ope.setOperationId(emp.getId());
            ope.setOperationName(emp.getEmpNm());
        }
        ope.setOperateType(OperateRecord.OPE_UPDATE);
        ope.setSourceId(oldCustomerCarModel.getId());
        operateRecordMapper.insert(ope);
        msg.success("修改成功");
        return msg;
    }

    /**
     * 删除
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseMsg<Object> deleteCarmodel(CustomerCarModel customerCarModel, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        //判断是否能删除
        CustomerCarModel carModel = customerCarModelMapper.selectById(customerCarModel);
        customerCarModelMapper.deleteById(customerCarModel);
        //添加操作日志
        OperateRecord ope = new OperateRecord();
        ope.setId(RandomHelper.uuid());
        if (empVo != null) {
            ope.setOperationId(empVo.getId());
            ope.setOperationName(empVo.getEmpNm());
        }
        ope.setOperateType("删除");
        ope.setSourceId(customerCarModel.getId());
        operateRecordMapper.insert(ope);
        msg.success("删除成功");
        return msg;
    }
}
